import React, { Component } from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Tools, SearchBar, Avatar, Icon, Button } from 'weaver-mobile';
import { ListViewPage, RouteLayout, SearchPage } from 'weaver-mobile-page';
import { renderNoData, renderLoading } from '../../util';
import BackTop from '../../public/back-to-top'
import Fill from '../fill';

const { getLabel, getWeaverFile } = Tools;

@withRouter
@inject('resultStore')
@observer
export default class PersonList extends Component {
  static defaultProps = {
    prefixCls: 'voting-result-person'
  }

  constructor(props) {
    super(props);
    this.getParams();
    let votingid = props.match.params && props.match.params.votingid;
    let questionid = props.match.params && props.match.params.id;
    this.state = {
      votingid: votingid || '',
      questionid: questionid || '',
      previewPath: '',
    }
  }

  componentWillMount () {
    const { resultStore: { personListStore } } = this.props;
    const { inital, search } = personListStore;
    this.getParams();
    inital();
    search();
  }

  componentWillUnmount() {
    const { resultStore: { personListStore } } = this.props;
    personListStore.clear();
  }

  getParams = () => {
    const { location: { pathname }, match: { path, params }, resultStore: { personListStore } } = this.props;
    if(/^\/[^/]+\/?/.test(pathname)) {
    //   let active = (path.match(/\/:votingid\/([\w].*\/)([\w].*)$/) && path.match(/\/:votingid\/([\w].*\/)([\w].*)$/)[2]);
    //   let _active = path.match(/\/:votingid\/([\w].*)$/) && path.match(/\/:votingid\/([\w].*)$/)[1];
    //   let __active = path.split('/:')[1] && path.split('/:')[1].split('/')[1];
    //   active = active || _active || __active;
        let active = (path.match(/\/:votingid\/([^/]+)$/) && path.match(/\/:votingid\/([^/]+)$/)[0].replace(/^\/:votingid\//, ''));
        let __active = path.split('/:')[1] && path.split('/:')[1].split('/')[1];
        active = active || __active;
    
      personListStore.setStoreState({ page: active, path: pathname, votingid: params.votingid || '', questionid: params.questionid || '', optionid: params.optionid || '' });
    }
  }

  openLink = (href) => {
    window.openLink(href);
  }

  onSearch = (value) => {
    const { resultStore: { personListStore } } = this.props;
    const { search, setStoreState, localeStorageKey } = personListStore;
    setStoreState({ searchValue: value })
    search({username: value});
    if (value !== '') {
      let searchHistory = localStorage.getItem(localeStorageKey);
      searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
      searchHistory = searchHistory.filter(h => h.key !== value);
      searchHistory.unshift({ key: value, name: value });
      localStorage.setItem(localeStorageKey, JSON.stringify(searchHistory));
    }
  }

  getTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const { prefixCls, resultStore: { personListStore } } = this.props;
          const curCls = `${prefixCls}-template`;
          const { fileList } = personListStore;
          const { resourceidspan, idspan, departmentspan, deptNamespan, operatedatespan, otherinputspan, imageUrlspan, id, resourceid, useranonyKey, useranony, randomFieldId } = data;
          let userName = resourceidspan || idspan;
          let department = departmentspan || deptNamespan;
          let headerProps = {name: userName, url: imageUrlspan || '', userId: (useranonyKey === '1' || useranony === '1') ? -99 : (resourceid || id), anonymous: useranonyKey === '1' || useranony === '1'};
          return (
            <div className={curCls}>
              <div className={`${curCls}-avatar`}>
                <Avatar {...headerProps} />
              </div>
              <div className={`${curCls}-userInfo`}>
                <div className='name'>{userName}</div>
                <div className='department-time'>
                  {department && <span className='department'>{department}</span>}
                  {operatedatespan && <span className='time'>{operatedatespan}</span>}
                </div>
                {otherinputspan && <div className='maintain' dangerouslySetInnerHTML={{__html: otherinputspan}}/>}
                {
                  toJS(fileList)[randomFieldId] && toJS(fileList)[randomFieldId].map(({imagefilename, fileSize, imagefileid}) => (
                    <div className='attachment'>
                      <div>
                        <Icon size='xxs' type="enclosure" />
                        <span className="name"
                        //  onClick={(e) => { // 调查暂不支持附件预览
                          // e.preventDefault(); 
                          // this.openLink(`/spa/document/static4mobile/index.html#/attach/${imagefileid}?votingId=${this.state.votingid}`)
                        // }}
                        >{`${imagefilename}(${fileSize}K)`}</span>
                      </div>
                      <Button inline size="small" onClick={(e) => {
                        e.preventDefault();
                        if(Tools.mobileDetect().is('iPhone')&&!Tools.mobileDetect().isEmobile()) {
                          window.open("/weaver/weaver.file.FileDownload?fileid="+imagefileid+"&download=1&requestid=0&votingId=" + this.state.votingid + "&download=1"+"&_ec_ismobile=true");
                        } else {
                          getWeaverFile("/weaver/weaver.file.FileDownload?fileid="+imagefileid+"&download=1&requestid=0&votingId=" + this.state.votingid + "&download=1"+`&_ec_ismobile=true`, 'iframe');
                        }
                      }}>{getLabel(31156, '下载')}</Button>
                    </div>
                  ))
                }
              </div>
            </div>
          )
        },
      }],
    };
    return newTemp;
  }

  render() {
    const { prefixCls, history, location: { pathname }, resultStore: { personListStore, joinViewLayout }, match: { params } } = this.props;
    const { list, page, loading, searchPageStore, localeStorageKey, searchValue, setStoreState, searchPageClear } = personListStore;
    const datas = toJS(list).data;
    return (
      <div className={prefixCls}>
        <SearchBar
          placeholder={getLabel('83869','请输入')}
          value={searchValue}
          onFocus={() => {
            history.push(searchPageStore.path);
            let searchHistory = localStorage.getItem(localeStorageKey);
            searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
            searchPageStore.list.setState({ data: searchHistory });
          }}
        />
        <div className={`${prefixCls}-listContainer`}>
          {
            loading ? renderLoading : datas.length === 0 ? renderNoData() : (
              <BackTop
                visibilityHeight='200'
                modal
                target='wm-list-view-page-modal-scrollview'
                aim={page}
              >
                <ListViewPage.Normal
                  className={page}
                  store={list}
                  getTemplate={this.getTemplate}
                  customHeight='100%'
                  onRowClick={(data) => {
                    page === 'resJoin' && params && history.push(`${pathname}/view/${params.votingid}?sourceid=${data.resourceid}`)
                  }}
                />
              </BackTop>
            )
          }
        </div>
        <SearchPage
          store={searchPageStore}
          type={1}
          placeholder={getLabel('83869','请输入')}
          searchValue={searchValue}
          rowKey="key"
          nameKey="name"
          onSubmit={this.onSearch}
          onChange={val => setStoreState({ searchValue: val })}
          onClear={searchPageClear}
        />
        <Route
          key={joinViewLayout.id}
          path={joinViewLayout.path}
          render={() => (
            <RouteLayout>
              <div key="join_view" className="wm-route-layout">
                <Fill type='view'/>
              </div>
            </RouteLayout>
          )}
        />
      </div>
    )
  }
}